import React from 'react'
import {findDOMNode} from 'react-dom'
import { withRouter } from 'react-router-dom'

class SearchBar extends React.Component{
    constructor(props){
        super(props)
        this.state={
            active:0,
            value:null
        }
    }
    componentDidMount(){
        document.addEventListener('click',this.handleClick)
    }
    componentWillUnmount(){
        document.removeEventListener('click',this.handleClick)
    }
    handleClick=(e)=>{
        var component = findDOMNode(this.component)
        if(component.contains(e.target)){
            this.setState({
                active:1
            })
        }
        else
        {
           this.setState({
               active:0
            })
        }
    }
    SetData=()=>{
        const info = document.getElementsByClassName('searchInput')[0].value
        this.setState({
            value:info
        })
    }
    toSearch=(e)=>{
        e.preventDefault();
        this.props.history.push({pathname:'/search',query:this.state.value})

    }
    render(){
        return(
            <div style={{height:'100%',display:'flex',justifyContent:'center',alignItems:'center'}}>
                <div className='searchCom' >
                    <div className='searchFrom' style={{display:'flex',alignItems:'center',position:'relative'}} ref={component=>this.component=component}>
                    <form onSubmit={(e)=>this.toSearch(e)}>
                        <input className='searchInput' defaultValue={this.state.value} onChange={()=>this.SetData()} placeholder={this.state.active===0?'探索掘金':'搜索文章/小册/标签/用户'} maxLength='32'  style={{boxSizing:'border-box',boxShadow:'none',outline:'none',overflow:'visible',width:120,padding:7.2,height:30,backgroundColor:'#F4F5F5',fontSize:'13px',borderRadius:'2px',color:'#666666',border:this.state.active===0?'none':'solid 1px #1E80FF'}}></input>
                    </form>
                    </div>
                </div>
            </div>
        )
    }
} 
export default withRouter(SearchBar)